﻿using BLL;
using IBLL;
using kang.Entitys.IdentityAuthentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tools;
using WebGrease.Css.Extensions;
using webMvc.Models.ViewModel;

namespace webMvc.Controllers
{
    public class UsersController : BaseController
	{
		IUserInfoService userInfosService = new UserInfoService();
		IDepartmentService departmentService = new DepartmentService();
		IUserRoleMapperService userRoleMapperService = new UserRoleMapperService();
		IRoleInfoService roleInfoService = new RoleInfoService();

		public JsonResult GetUsersPage(int pageindex)
		{
			int count = 0;
			var ListResult = userInfosService.LoadPageEntities(pageindex, 10, out count, x => true, x => x.Id, true).ToList();
			return Json(ListResult);
		}

		public JsonResult GetUserDatas(UserTableParameter SearchParameter)
		{
			TableResult<UserInfo> tableResult = new TableResult<UserInfo>();
			tableResult.rows = userInfosService.LoadPageEntities(SearchParameter.pageNum, SearchParameter.pageSize, out tableResult.total, x => true, x => x.SubTime, true).ToList();
			return Json(tableResult, JsonRequestBehavior.AllowGet);
		}

		public ActionResult UserManage()
		{
			return View();
		}

		[HttpPost]
		public JsonResult AddUser(addUserViewModel addUserViewModel)
		{
			var userModel = userInfosService.AddDonator(new UserInfo()
			{
				SubTime = DateTime.Now,
				Uname = addUserViewModel.loginName,
				Modifdon = addUserViewModel.userName,
				Upwd = MD5Helper.MakeMD5(addUserViewModel.password, 32)
			});
			userInfosService.CurrentDbSession.allSaveChangge();

			foreach (string roleId in addUserViewModel.roleIds.Split(','))
			{
				userRoleMapperService.AddDonator(new UserRoleMapper()
				{
					Roleid = int.Parse(roleId),
					Userid = userModel.Id
				});
			}
			userInfosService.CurrentDbSession.allSaveChangge();

			return Json(new MyJsonResult() { code = 0, msg = "成功" });
		}

		public ActionResult AddUser()
		{
			Dictionary<int, string> RoleIdAndName = new Dictionary<int, string>();
			roleInfoService.LoadEntities(x => true).Select(x => new { id = x.Id, name = x.RoleName }).ToArray().ForEach(x => RoleIdAndName.Add(x.id, x.name));
			//设BLL类可以抓到数据,RoleIdAndName中有值吗?如果没有如何才能填充值
			ViewBag.roleIdAndList = RoleIdAndName.ToArray();
			return View();
		}


	}
}